package com.pp.demo.module.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.pp.demo.module.user.dto.UserRoleDTO;
import com.pp.demo.module.user.entity.UserRole;
import com.pp.demo.module.user.mapper.UserRoleMapper;
import com.pp.demo.module.user.service.UserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pzh
 * @since 2025-07-05 06:01:59
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public List<String> getRoleNamesByUserId(Long userId) {
        List<String> userRoles = new ArrayList<>();

        List<UserRoleDTO> dtos = userRoleMapper.listUserRole(userId);
        if (CollUtil.isNotEmpty(dtos)) {
            for (UserRoleDTO dto : dtos) {
                userRoles.add(dto.getRoleName());
            }
        }
        return userRoles;
    }

    @Override
    public void saveUserRoles(Long userId, List<Long> roleIds) {
        List<UserRole> userRoles = new ArrayList<>();
        if (CollUtil.isNotEmpty(roleIds)) {
            for (Long roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoles.add(userRole);
            }
        }
        this.saveBatch(userRoles);
    }
}
